import { API_BASE_URL } from './config';
import store from '../store';

/**
 * 核心请求函数
 * @param {object} options - uni.request的参数
 */
const coreRequest = (options) => {
  return new Promise((resolve, reject) => {
    // 1. 统一的请求头
    const token = store.state.user.token || uni.getStorageSync('token');
    const header = {
      ...options.header,
      'Authorization': token ? `Bearer ${token}` : ''
    };

    // 2. 发起请求
    uni.request({
      ...options,
      header,
      success: (res) => {
        // 3. 统一的响应处理
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 后端自定义的code也需要判断
          if (res.data.code === 200) {
            resolve(res.data);
          } else {
            uni.showToast({ title: res.data.message || '请求失败', icon: 'none' });
            reject(res.data);
          }
        } else {
          // HTTP状态码错误
          uni.showToast({ title: `网络错误 ${res.statusCode}`, icon: 'none' });
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({ title: '请求失败，请检查网络', icon: 'none' });
        reject(err);
      }
    });
  });
};

/**
 * 导出的api对象, 包含GET, POST, PUT, DELETE方法
 */
export const api = {
  get(url, data = {}, options = {}) {
    return coreRequest({ ...options, url: API_BASE_URL + url, method: 'GET', data });
  },
  post(url, data = {}, options = {}) {
    return coreRequest({ ...options, url: API_BASE_URL + url, method: 'POST', data });
  },
  put(url, data = {}, options = {}) {
    return coreRequest({ ...options, url: API_BASE_URL + url, method: 'PUT', data });
  },
  delete(url, data = {}, options = {}) {
    return coreRequest({ ...options, url: API_BASE_URL + url, method: 'DELETE', data });
  }
};

/**
 * 统一上传文件函数
 */
export const uploadFile = (options) => {
  return new Promise((resolve, reject) => {
    const token = store.state.user.token || uni.getStorageSync('token');
    // 允许传入自定义上传路径，否则使用默认的通用上传路径
    const uploadUrl = options.url ? (API_BASE_URL + options.url) : `${API_BASE_URL}/file/upload`;

    // --- Start Debugging ---
    console.log('[uploadFile] Initiating upload...');
    console.log('[uploadFile] Options received:', JSON.stringify(options));
    console.log('[uploadFile] API_BASE_URL:', API_BASE_URL);
    console.log('[uploadFile] Final Upload URL:', uploadUrl);
    // --- End Debugging ---

    uni.uploadFile({
      url: uploadUrl,
      filePath: options.filePath,
      name: options.name || 'file',
      formData: options.formData || {},
      header: {
        'Authorization': token ? `Bearer ${token}` : ''
      },
      success: (uploadRes) => {
        if (uploadRes.statusCode === 200) {
          const res = JSON.parse(uploadRes.data);
          if (res.code === 200) {
            resolve(res);
          } else {
            uni.showToast({ title: res.message || '上传失败', icon: 'none' });
            reject(res);
          }
        } else {
          uni.showToast({ title: `上传失败 ${uploadRes.statusCode}`, icon: 'none' });
          reject(uploadRes);
        }
      },
      fail: (err) => {
        uni.showToast({ title: '上传接口调用失败', icon: 'none' });
        reject(err);
      }
    });
  });
}; 